﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;

namespace DotNetStar.TheKing.Web.Controllers
{
    using Services;
    using DotNetStar.TheKing.Infrastructure;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.Extensions.Logging;
    using Microsoft.AspNetCore.Hosting;

    [Route("[controller]"),AllowAnonymous]
    public class AccountController : Controller
    {
         UserService _userService;
        VerifyCodeService _verifyCodeService;        
        private readonly ILogger<AccountController> _logger;
        private readonly IHostingEnvironment _environment;

        public AccountController(UserService userService,
            VerifyCodeService verifyCodeService,
            IHostingEnvironment environment,
            ILogger<AccountController> logger
            )
        {
            this._userService = userService;
            this._verifyCodeService = verifyCodeService;
            _logger = logger;
            _environment = environment;
        }

        /// <summary>
        /// 发验证码。
        /// </summary>
        /// <param name="account">帐号，手机号/邮箱</param>
        /// <param name="needExist">是否必须存在才能发消息，true 存在才发送，false 不存在才发送</param>
        /// <returns></returns>
        [HttpPost("/api/sms")]
        public async Task<IActionResult> SendVerifyCodeAsync(string account,bool needExist=true)
        {
            if (account.IsNullOrWhiteSpace())
            {
                return this.ApiStatus(StatusCodeEnums.BadRequest);
            }


            try
            {
                if (_environment.IsDevelopment())
                {
                    account = "15011052050";
                }
                var user = _userService.GetUserAsync(account, out AccountTypes accountType);
                if (await user == null && needExist)
                {
                    switch (accountType)
                    {
                        case AccountTypes.Email:
                            return this.ApiStatus(StatusCodeEnums.BadRequest, "邮箱不存在");
                        case AccountTypes.Mobile:
                            return this.ApiStatus(StatusCodeEnums.BadRequest, "手机不存在");
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
                

                _verifyCodeService.PutVerifyCode(account, accountType);

                return Ok();
            }
            catch (Exception ex)
            {
                _logger.LogError(new EventId((int)StatusCodeEnums.ServerInternalError, StatusCodeEnums.ServerInternalError.GetDescription()), ex, ex.Message);
                return this.ApiStatus(StatusCodeEnums.ServerInternalError);
            }
        }

        /// <summary>
        /// 检测帐号是否存在
        /// </summary>
        /// <param name="account">The account.</param>
        /// <returns>如果存在则为 <c>true</c>；否则为 <c>false</c></returns>
        [HttpPost("/api/account/check")]
        public async Task<IActionResult> CheckAccountExistAsync([FromForm]string account)
        {
            var user = await _userService.GetUserAsync(account, out AccountTypes accountType);
            return Json(new { exist = user != null, type = accountType.GetDescription() });
        }



        /// <summary>
        /// 判断是否签到
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/signin")]
        public async Task<IActionResult> IsSignInAsync()
        => Json( await _userService.IsUserSignInTotayAsync(User.Identity.UserId()));


        /// <summary>
        /// 签到
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/signin")]
        public async Task<IActionResult> SignInAsync()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Json(false);
            }
            var result = await _userService.SignInAsync(User.Identity.UserId());
            return Json(result.Data);
        }

        [HttpGet("/api/users")]
        public async Task<IActionResult> GetUsersAsync(string userName,int top)
        {
            var users = await _userService.GetUsersAsync(m => m.UserName.Contains(userName));
            return Json(users);
        }
    }
}